<template>
  <div class="address">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>收货地址管理</h2>
          <el-button type="primary" @click="openAddressDialog()">新增地址</el-button>
        </div>
      </template>

      <div v-if="addressList.length === 0" class="empty-tip">暂无收货地址，请添加</div>

      <div v-else class="address-list">
        <el-card v-for="(address, index) in addressList" :key="index" class="address-item">
          <div class="address-content">
            <div class="address-info">
              <p>
                <span class="recipientName" style="margin-right: 10px">用户：{{
                  address.recipientName
                }}</span>
                <span class="phone">手机号：{{ address.phone }}</span>
              </p>
             <p class="address-addressDetail">
                {{ address.province }} {{ address.city }} {{ address.district }}
                详细地址 ： {{ address.addressDetail }}
              </p>
            </div>
            <div class="address-actions">
              <el-button type="primary" size="small" @click="openAddressDialog(address)"
                >编辑</el-button
              >
              <el-button type="danger" size="small" @click="deleteAddress(address)">删除</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 地址编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑地址' : '新增地址'" width="50%">
      <el-form :model="addressForm" label-width="100px">
        <el-form-item label="收货人">
          <el-input v-model="addressForm.recipientName" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>

        <el-form-item label="手机号码">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>

        <el-form-item label="详细地址">
          <el-input
            v-model="addressForm.addressDetail"
            type="textarea"
            placeholder="请输入详细地址"
          ></el-input>
        </el-form-item>

        <el-form-item> </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAddress">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listAddress, getAddress, addAddress, updateAddress, delAddress } from '@/api/address'

// 地址列表
const addressList = ref([])

// 对话框显示状态
const dialogVisible = ref(false)

// 是否为编辑模式
const isEdit = ref(false)

// 地址表单
const addressForm = reactive({
  id: null,
  userId: null,
  recipientName: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  addressDetail: '',
})

// 获取地址列表
const getAddressList = async () => {
  try {
    // 获取当前用户ID
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const userId = userInfo.id

    if (!userId) {
      ElMessage.error('用户信息不存在，请重新登录')
      return
    }

    const res = await listAddress({ userId })
    addressList.value = res.data || []
  } catch (error) {
    console.error('获取地址列表失败', error)
    ElMessage.error('获取地址列表失败')
  }
}

// 打开地址对话框
const openAddressDialog = (address) => {
  if (address) {
    // 编辑模式
    isEdit.value = true
    Object.assign(addressForm, address)
  } else {
    // 新增模式
    isEdit.value = false
    // 重置表单
    Object.assign(addressForm, {
      id: null,
      userId: JSON.parse(localStorage.getItem('userInfo') || '{}').id,
      recipientName: '',
      phone: '',
      province: '',
      city: '',
      district: '',
      addressDetail: '',
    })
  }

  dialogVisible.value = true
}

// 保存地址
const saveAddress = async () => {
  try {
    // 表单验证
    if (!addressForm.recipientName) {
      ElMessage.warning('请输入收货人姓名')
      return
    }

    if (!addressForm.phone) {
      ElMessage.warning('请输入手机号码')
      return
    }

    if (!addressForm.addressDetail) {
      ElMessage.warning('请输入详细地址')
      return
    }

    if (isEdit.value) {
      // 编辑地址
      await updateAddress(addressForm)
      ElMessage.success('地址更新成功')
    } else {
      // 新增地址
      await addAddress(addressForm)
      ElMessage.success('地址添加成功')
    }

    // 关闭对话框
    dialogVisible.value = false

    // 刷新地址列表
    getAddressList()
  } catch (error) {
    console.error('保存地址失败', error)
    ElMessage.error('保存地址失败')
  }
}

// 删除地址
const deleteAddress = (address) => {
  ElMessageBox.confirm(`确定要删除 ${address.recipientName} 的收货地址吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await delAddress(address.id)
        ElMessage.success('地址删除成功')
        getAddressList()
      } catch (error) {
        console.error('删除地址失败', error)
        ElMessage.error('删除地址失败')
      }
    })
    .catch(() => {})
}

// 初始化
onMounted(() => {
  getAddressList()
})
</script>
